<template>
    <!-- 大屏主要部分组件 -->
    <div class="page-main">
      <!-- 左侧部分 -->
      <div class="page-left">
        <!-- 新用户增长情况 --> 
        <div class="left-userInfo">
            <div ref="userChartDom" class="user-chart"></div>
            <span class="user-tip">近七日新用户注册量</span>
        </div>
        <!-- 订单增长情况 -->
        <div class="left-orderInfo">
            <div ref="orderChartDom" class="order-chart"></div>
            <span class="order-tip">近七日下单数量</span>
        </div>      
      </div>
      <!-- 中间部分 -->
      <div class="page-center">
        <!-- 地图部分 -->
        <div class="center-map">
          <Map></Map>
        </div>
        <div class="center-info">
          <span class="center-info-tip">用户所在省份分布情况</span>
        </div>
      </div>
      <!-- 右侧部分 -->
      <div class="page-right">
        <!-- 网站销量高的商品所占比例 -->
        <div class="right-productInfo">
            <div ref="productChartDom" class="product-chart"></div>
            <span class="product-tip">站点销售量高的商品分布情况</span>
        </div>
        <!-- 右侧下部分区域 -->
        <div class="right-other">
          <div class="other-left">
            <span class="left-title">通知公告:</span>
            <div class="left-info">
              <span class="info-item">网站用户数: {{ screenData.userCount }}</span>
              <span class="info-item">网站商品分类数: {{ screenData.commodityCategoryCount }}</span>
              <span class="info-item">网站商品总数: {{ screenData.commodityCount }}</span>
              <span class="info-item">网站订单成交数: {{ screenData.orderCount_accomplish }}</span>
              <span class="info-item">网站商品总销售额: {{ screenData.saleMoneyTotal }}</span>
            </div>
          </div>
          <div class="other-null"></div>
          <div class="other-right">
            <span class="right-title">实时状态:</span>
            <div class="right-info">
              <span class="info-item">异常订单数: {{ screenData.orderCount_abnormal }}</span>
              <span class="info-item">待处理订单数: {{ screenData.orderCount_pending }}</span>
              <span class="info-item">订单投诉数: {{ screenData.orderCount_complain }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>
</template>

<script setup lang='ts'>
import { ref, reactive, onMounted, onUnmounted } from "vue";
//引入子组件
import Map from "./map.vue";
//引入echarts
import * as echarts from "echarts";
//引入请求函数
import { reqUserList, reqOrderList, reqCommodityListSort, reqMemberCount, reqCommodityCategory, reqOrderListByState } from "@/api/screen/index.ts";

//用户增长情况dom实例对象
let userChartDom = ref();
//订单情况图表dom实例
let orderChartDom = ref();

//近七日日期情况 --> [{id: 7, day: '2日', formattedDate: '2024-03-02 11:41:29'},...]
let dayList = ref<Object[]>([]);

//大屏右下角信息部分数据
let screenData = reactive({
  userCountListByServenDay:[10,9,6,1,8,12,15],  //近七天注册的会员用户人数
  createOrderListByServenDay:[1,2,3,2,5,0,2],  //近七天创建的订单列表总数
  fashionCommodityList:[{name:"",value:0}],  //实时销量最高的前五款商品
  userCount:0,  //网站用户总数
  commodityCategoryCount:0,  //商品分类数
  commodityCount:0,  //商品总数
  orderCount_accomplish:0,  //订单成交数
  orderCount_pending:0,  //待处理订单数
  saleMoneyTotal:0,  //网站商品销售总额
  orderCount_abnormal:0,  //异常订单数
  orderCount_complain:0  //投诉订单数
})

const userChartOption = {
  xAxis: {
    type: 'category',
    data: ['1日', '2日', '3日', '4日', '5日', '6日', '7日']
  },
  yAxis: {
    type: 'value'
  },
  series: [
    {
      data: [150, 230, 224, 218, 135, 147, 260],
      type: 'line'
    }
  ]
};
const orderChartOption = {
  xAxis: {
    type: 'category',
    data: ['1日', '2日', '3日', '4日', '5日', '6日', '7日']
  },
  yAxis: {
    type: 'value'
  },
  series: [
    {
      data: [120, 200, 150, 80, 70, 110, 130],
      type: 'bar'
    }
  ]
};
//生成近七日新用户注册情况折线图
const drawUserChart = () => {
    echarts.init(userChartDom.value).setOption(userChartOption);
}
//生成近七日订单数量情况柱状图
const drawOrderChart = () => {
    echarts.init(orderChartDom.value).setOption(orderChartOption);
}

//网站销售靠前的商品占比例饼图
let productChartDom = ref();
const productChartOption = {
  tooltip: {
    trigger: 'item'
  },
  legend: {
    top: '5%',
    left: 'center'
  },
  series: [
    {
      name: '网红商品分布情况',
      type: 'pie',
      radius: ['40%', '70%'],
      avoidLabelOverlap: false,
      label: {
        show: false,
        position: 'center'
      },
      emphasis: {
        label: {
          show: true,
          fontSize: 40,
          fontWeight: 'bold'
        }
      },
      labelLine: {
        show: false
      },
      data: [
        { value: 1048, name: '无骨鸡爪' },
        { value: 735, name: '预制菜' },
        { value: 580, name: '小家电' },
        { value: 484, name: '烧烤架' },
        { value: 300, name: '墙纸' }
      ]
    }
  ]
}
//生成网站销售靠前的商品占比例饼图
const drawProductChart = () => {
    echarts.init(productChartDom.value).setOption(productChartOption);
}

//获取当前日期并推算出前六天
function getDayList () {
  let days = [];
  //获取当前时间戳
  let timestape = Date.now();
  let count = 0;
  for(let i = 6; i >= 0; i --) {
    count ++;
    let day = new Date(timestape - (i * 1000 * 60 * 60 * 24)).getDate() + "日";  // 1日,2日..
    let formattedDate = formatTimestamp(timestape - (i * 1000 * 60 * 60 * 24));
    days.push({id:count, day, formattedDate, startTime:formatTimestamp(timestape - (i * 1000 * 60 * 60 * 24),1), endTime:formatTimestamp(timestape - (i * 1000 * 60 * 60 * 24),2), startDate:formatTimestamp(timestape - (i * 1000 * 60 * 60 * 24),4), endDate:formatTimestamp(timestape - (i * 1000 * 60 * 60 * 24),3), num:0});
  }
  //赋值
  dayList.value = days;
  //更新echarts表单配置:日期
  userChartOption.xAxis.data = days.map(item => {
    return item.day
  })
  orderChartOption.xAxis.data = days.map(item => {
    return item.day;
  })
}
//格式化时间对象 yyyy-MM-dd //hh:mm:ss
function formatTimestamp(timestamp:number,type?:number = 0) {
    const date = new Date(timestamp);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const reduceDay = String(new Date(timestamp - (1000*60*60*24)).getDate()).padStart(2,'0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    const seconds = String(date.getSeconds()).padStart(2, '0');
    let formattedDate = "";
    switch (type) {
      case 0:
        formattedDate = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        break;
      case 1:
        formattedDate = `${year}-${month}-${day} 00:00:00`;
        break;
      case 2:
        formattedDate = `${year}-${month}-${day} 23:59:59`;
        break;
      case 3:
        formattedDate = `${year}-${month}-${day}`;
        break;
      case 4:
        formattedDate = `${year}-${month}-${reduceDay}`;
        break;
      default:
        formattedDate = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        break;
    }   
    return formattedDate;
}

//获取注册会员信息(某天内注册的用户数)
const getUserListByDate = async () => {
  let userCountList = [];
  for (let i = 0; i < dayList.value.length; i++) {
    let res = await reqUserList(dayList.value[i].startTime,dayList.value[i].endTime);
    if(typeof res.data === "string"){
      userCountList.push(0);
    } else {
      userCountList.push(res.data.total);
    }
    console.log("获取某段时间内平台注册的会员用户信息",res); 
  }
  screenData.userCountListByServenDay = userCountList;
  userChartOption.series[0].data = userCountList;
  drawUserChart();  //绘制近七日新用户注册量图表
}
//获取订单信息(某天内创建的订单数)
const getOrderListByDate = async () => {
  let orderCountList = [];
  for (let i = 0; i < dayList.value.length; i++) {
    let res = await reqOrderList(dayList.value[i].startDate, dayList.value[i].endDate);
    if(typeof res.data === "string"){
      orderCountList.push(0);
    } else {
      orderCountList.push(res.data.total);
    }
    console.log("获取某段时间内平台订单创建信息",res); 
  }
  screenData.createOrderListByServenDay = orderCountList;
  orderChartOption.series[0].data = orderCountList;
  console.log(orderCountList);
  drawOrderChart();  //绘制近七日下单数量图表
}
//获取所有商品信息，已根据销量进行了排序，前端截取前五项数据展示
const getCommodityListByCommoditySalesSort = async () => {
  let res = await reqCommodityListSort();
  //商品总数
  screenData.commodityCount = res.data.total;

  //销量最高的前五项商品
  let commoditySalesList = res.data.rows.slice(0,5).map(item => {
    return {
      name:item.commodityName,
      value:item.commoditySales
    }
  })
  screenData.fashionCommodityList = commoditySalesList;
  console.log('获取所有商品信息api,已根据销量信息进行了降序排序',res);
  productChartOption.series[0].data = commoditySalesList;
  drawProductChart();  //绘制站点销售量高的商品分布情况图表
}
//获取网站平台会员用户总数
const getMemberTotal = async () => {
  let res = await reqMemberCount();
  screenData.userCount = res.data.memberCount || 0;
  console.log('获取平台会员总数api',res);
}
//获取平台商品分类总数
const getCommodityCategoryTotal = async () => {
  let res = await reqCommodityCategory();
  screenData.commodityCategoryCount = res.data.total || 0;
  console.log('获取平台所有商品分类信息api',res);
}
//根据订单状态查询订单信息(订单成交数/商品销售总额)
const getOrderListByState = async () => {
  let res = await reqOrderListByState("已评价");
  if(typeof res.data == "string"){
    //未查询到数据
    screenData.orderCount_accomplish = 0;  //订单成交数
    screenData.saleMoneyTotal = 0;  //商品销售总额
  } else {
    //有数据
    screenData.orderCount_accomplish = res.data.total;
    let count = 0;
    res.data.rows.forEach(item => {
      count += item.orderTotalPrice;
    })
    screenData.saleMoneyTotal = count;
  }
  console.log('根据订单状态查询订单信息api:已完成',res);
  let response1 = await reqOrderListByState("已支付");
  let response2 = await reqOrderListByState("待发货");
  let count1 = 0, count2 = 0;
  if(typeof response1.data == "string"){
    count1 = 0;
  } else {
    count1 = response1.data.total;
  }
  if(typeof response2.data == "string"){
    count2 = 0;
  } else {
    count2 = response2.data.total;
  }
  screenData.orderCount_pending = (count1 + count2);
  console.log('根据订单状态查询订单信息api:已支付',response1);
  console.log('根据订单状态查询订单信息api:待发货',response2);
}

//用一个总的函数来请求所用的资源
function reqAllSource () {
  //请求大屏所用数据资源
  getUserListByDate();
  getOrderListByDate();
  getCommodityListByCommoditySalesSort();
  getMemberTotal();
  getCommodityCategoryTotal();
  getOrderListByState();
}

//定时实时更新大屏数据 time = 2分钟
let timer:any = null;
const getScreenInfoRealTime = () => { 
  if(timer !== null) clearInterval(timer);
  timer = setInterval(() => {
    reqAllSource();  //每隔两分钟请求一次资源
  },1000 * 60 * 2)
}

//vue生命周期
onMounted(() => {
  //生成近七日天数
  getDayList();
  //请求大屏数据资源并对所有的图表进行初始化
  reqAllSource();
  //开启定时器实时请求大屏资源
  getScreenInfoRealTime();
})
onUnmounted(() => {
  //清除定时器
  clearInterval(timer);
})
</script>
<script lang="ts">
export default {
    name:"ScreenMain"
}
</script>

<style lang='scss' scoped>
.page-main{
    width: 100%;
    height: 100%;
    display: flex;

    /**左侧部分 */
    .page-left {
        flex:1;
        display: flex;
        flex-direction: column;
        .left-userInfo{
            flex: 1;
            display: flex;
            flex-direction: column;
            .user-chart{
                flex: 1;
            }
            .user-tip{
                position: relative;
                margin: 0 auto;
                top:-25px;
                font-size: 20px;
                color: #9195a3;
            }
        }
        .left-orderInfo{
            flex: 1;
            display: flex;
            flex-direction: column;
            .order-chart{
                flex:1;
            }
            .order-tip{
                position: relative;
                margin: 0 auto;
                top:-25px;
                font-size: 20px;
                color: #9195a3;
            }
        }
    }
    .page-center{
        flex:3;
        display: flex;
        flex-direction: column;
        .center-map{
          width: 1100px;
          height: 900px;
        }
        .center-info{
          text-align: center;
          font-size: 20px;
          color: #9195a3;
        }
    }
    /**右侧部分 */
    .page-right{
        flex:1;
        display: flex;
        flex-direction: column;
        .right-productInfo{
            flex: 1;
            display: flex;
            flex-direction: column;
            .product-chart{
                flex: 1;
            }
            .product-tip{
                position: relative;
                margin: 0 auto;
                top:-50px;
                font-size: 20px;
                color: #4d4f53;
            }
        }
        .right-other{
            flex: 1;
            background-color: rgba($color: #dbdbda, $alpha: 0.3);
            padding: 30px;
            box-sizing: border-box;
            display: flex;
            flex-direction: column;
            .other-left{
              flex:4;
              display: flex;
              flex-direction: column;
              .left-title{
                flex: 1;
                font-size: 20px;
              }
              .left-info{
                flex: 5;
                display: flex;
                flex-direction: column;
                .info-item{
                  margin: 10px 0;
                }
              }
            }
            .other-null{
              flex:1;
            }
            .other-right{
              flex:3;
              display: flex;
              flex-direction: column;
              .right-title{
                flex: 1;
                font-size: 20px;
              }
              .right-info{
                flex: 5;
                display: flex;
                flex-direction: column;
                .info-item{
                  margin: 10px 0;
                }
              }
            }
        }
    }
}

</style>